//
//  YCLStatusViewModel.swift
//  新浪微博01
//
//  Created by yaochunlin on 16/4/13.
//  Copyright © 2016年 yaochunlin. All rights reserved.
//

import UIKit
import AFNetworking
import SDWebImage

class YCLStatusViewModel: NSObject {
    
    private var loadStatusing:Bool = false
    //单例
    static let sharedStatusViewModel: YCLStatusViewModel = YCLStatusViewModel()
    
    //加载微博数据
    func loadStatusData(since_id: Int64, max_id: Int64, callBack:(statuses:[YCLStatus]? , error: NSError?) ->()){
        
        //判断是否有人在加载微博
        if loadStatusing {
            
            YCLPrint("有人在加载微博数据")
            return
        }
        
        loadStatusing = true
        
        //        // 1.urlString
        //        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //
        //        // 2.参数
        //        var parameters: [String : AnyObject] = ["access_token": YCLUserAccountViewModel.sharedUserAccountViewModel.userAccount!.access_token!]
        //
        //        //拼接参数
        //        if since_id > 0 {
        //            parameters["since_id"] = NSNumber(longLong: since_id)
        //        }else if max_id > 0 {
        //
        //            parameters["max_id"] = NSNumber(longLong: max_id - 1)
        //        }
        YCLPrint("since_id: \(since_id), max_id:\(max_id)")
        
        //        //TODO: 从数据库加载微博数据
        //        YCLStatusDAL.sharedStatusDAL.loadCacheStatus(since_id, max_id: max_id) { (statusDicts) in
        //
        //            if statusDicts == nil || statusDicts?.count == 0 {
        //
        //                YCLPrint("本地数据库没有数据")
        //                return
        //            }
        //            YCLPrint("从本地数据库加载了数据\(statusDicts)")
        //        }
        //从DAL获取数据
        YCLStatusDAL.sharedStatusDAL.loadStatus(since_id, max_id: max_id) { (statusDicts, error) in
            //加载完成将状态改为false
            self.loadStatusing = false
            
            if error != nil {
                
                YCLPrint("加载数据错误:\(error)")
                callBack(statuses: nil, error: error)
                return
            }
            
            //创建可变模型数组
            var statusModels = [YCLStatus]()
            //遍历字典数组
            for dict in statusDicts!{
                
                let status = YCLStatus(dict: dict)
                
                statusModels.append(status)
            }
            
            //                callBack(statuses: statusModels, error: nil)
            //缓存图片
            self.cacheWebImage(statusModels, callBack: callBack)
            
            
        }
    }
    
    
    //        YCLNetworkTool.sharedNetworkTool.GET(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) in
    //
    //            //YCLPrint("获取微博数据成功\(responseObject)")
    //            //加载完成将状态改为false
    //            self.loadStatusing = false
    //
    //            //将数据转化为模型
    //            if let dict = responseObject as? [String:AnyObject], let statusesDict = dict["statuses"] as? [[String:AnyObject]]{
    //
    //                //TODO: 测试保存数据到数据库
    //                YCLStatusDAL.sharedStatusDAL.saveCacheStatus(statusesDict)
    //
    //                //创建可变模型数组
    //                var statusModels = [YCLStatus]()
    //                //遍历字典数组
    //                for dict in statusesDict{
    //
    //                    let status = YCLStatus(dict: dict)
    //
    //                    statusModels.append(status)
    //                }
    //
    //                //                callBack(statuses: statusModels, error: nil)
    //                //缓存图片
    //                self.cacheWebImage(statusModels, callBack: callBack)
    //
    //            }
    //
    //        }) { (task, error) in
    //
    //            //                YCLPrint("获取微博数据失败\(error)")
    //
    //            callBack(statuses: nil, error: error)
    //        }
    //    }
    
    //缓存微博图片
    private func cacheWebImage(statuses: [YCLStatus], callBack:(statuses:[YCLStatus]? , error: NSError?) ->()){
        
        //创建任务组
        let group = dispatch_group_create()
        
        //判断每个模型是否有图片要下载
        for status in statuses {
            
            var downloadURLS:[NSURL]?
            downloadURLS = status.storePictureURLs
            
            //首先看原创有不有图片要下载
            if downloadURLS == nil {
                
                //若没有则看转发的有不有图片要下载
                downloadURLS = status.retweeted_status?.storePictureURLs
            }
            
            if let urls = downloadURLS {
                
                //只有一张图片的时候需要从网上下载，多张时候可以等tableview加载时再去下载
                if urls.count == 1 {
                    
                    //取出第一张图片
                    let url = urls.first
                    
                    //进组
                    dispatch_group_enter(group)
                    
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (image, error, _, _, _) in
                        
                        //异步任务完成会调用这个闭包
                        //离开组
                        dispatch_group_leave(group)
                        
                        if error != nil {
                            
                            YCLPrint("图片下载失败\(error)")
                            return
                        }
                        
                        // YCLPrint("图片下载成功:\(url)")
                    })
                    
                }
            }
            
        }
        
        //监听所有微博下载图片完成
        
        dispatch_group_notify(group, dispatch_get_main_queue()) {
            
            //            YCLPrint("SD下载图片完成")
            callBack(statuses: statuses,error: nil)
        }
        
    }
    
    //发送不带图片的微博数据
    //发送微博数据
    func sendStatus(status: String, image:UIImage? , callBack:(error: NSError?) ->()) {
        
        guard let access_token = YCLUserAccountViewModel.sharedUserAccountViewModel.userAccount?.access_token else{
            
            YCLPrint("access_token为空值")
            return
            
        }
        
        var parameters = ["access_token": access_token , "status":status]
        
        //无图片微博
        if image == nil {
            
            let urlString = "https://api.weibo.com/2/statuses/update.json"
            
            YCLNetworkTool.sharedNetworkTool.POST(urlString, parameters: parameters, progress: nil, success: { (_, responseObject) in
                
                callBack(error: nil)
                
            }) { (_, error) in
                
                YCLPrint("出错了:\(error)")
                callBack(error: error)
            }
        }else{
            
            //有图片微博
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            YCLNetworkTool.sharedNetworkTool.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formdata) in
                
                //需要传入图片
                //将图片转化为二进制
                let imgData = UIImagePNGRepresentation(image!)
                /*!
                 data: 要上传文件的二进制
                 name: 接口文档指定上传字段名称
                 fileName: 保存在服务器的文件名称，有文档规定按文档来，没有可以随意
                 mimeType: 类型
                 */
                formdata.appendPartWithFileData(imgData!, name: "pic", fileName: "aab", mimeType: "image/png")
                }, success: { (_, responseObject) in
                    
                    //成功回调
                    callBack(error: nil)
                }, failure: { (_, error) in
                    
                    //失败回调
                    callBack(error: error)
            })
            
        }
        
        
    }
    
    
}
